/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package ticketbooking;

import MessageVariable.ServerSign;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.SealedObject;

/**
 *
 * @author Kse7en
 */
public class Listenner implements Runnable{
     ServerSocket serverSock = null;
     ServerKey serverKey = null;
     public Listenner(ServerSocket sock, ServerKey key){
           this.serverSock = sock;
           this.serverKey = key;
     }
     @Override
     public void run(){
         while(true){
             try {
                 Socket sessionSocket = serverSock.accept();
                 ObjectOutputStream out = new ObjectOutputStream(sessionSocket.getOutputStream());
                 ObjectInputStream in = new ObjectInputStream(sessionSocket.getInputStream());
                 Object o = in.readObject();
                 if(o != null){
                    if(o instanceof TransferMessage){
                        TransferMessage connectMsg = (TransferMessage)o;
                        if(connectMsg.getType() == TransferMessage.CONNECT){
                            TransferMessage rsp = new TransferMessage();
                            rsp.setType(TransferMessage.ACK);
                            ServerSign serverSign = new ServerSign(sessionSocket.getLocalAddress().getHostAddress(), sessionSocket.getLocalPort(),serverKey.getPublicKeyRSA(), serverKey.getPubliKeySign());
                            rsp.setServerSign(serverSign);
                            out.writeObject(rsp);
                            Thread thread = new Thread(new RemoteController(serverSign, connectMsg.getClientSign(), serverKey, sessionSocket));
                            thread.start();
                        }
;                    }
                 }
             } catch (Exception ex) {
                 Logger.getLogger(Listenner.class.getName()).log(Level.SEVERE, null, ex);
             }
         }
     }
}
